<?php
/**
 * 活动管理
 */
namespace Admin\Controller;
use Admin\BaseController;

use Common\Model\HouseWorkModel;
use Common\Model\SmsModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;

use Think\Page;
/*Ajax异步获取数据Action*/
class HouseWorkController extends BaseController{

	/**
	 * 上线的业务
	 * Author: shijy
	 */
	public function index(){
		$actype = I('get.actype','online','trim');
		$this->smarty->assign('actype',$actype);
		switch ($actype){
			case 'online': $this->online(); break;
			case 'offline': $this->offline(); break;
		}
	}
	private function online(){
		$where='status='.HouseWorkModel::STATUS_ONLINE.' and beginShowTime<'.time();
		$eventsM = HouseWorkModel::getItemInstance();
		import("ORG.Util.Page");

		$temp=$eventsM->where($where);
		$count = $temp->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);

		$list = $eventsM->order('beginShowTime DESC')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

		//var_dump($list);die;

		$this->smarty->assign('list',$list);
		$this->smarty->assign('limit',$limit);


		$this->smarty->display('HouseWork/index_online.html');
	}
	private function offline(){
		$where='status='.HouseWorkModel::STATUS_OFFLINE.' OR beginShowTime>'.time();

		$eventsM = HouseWorkModel::getItemInstance();
		import("ORG.Util.Page");

		$temp=$eventsM->where($where);
		$count = $temp->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);

		$list = $eventsM->order('beginShowTime DESC')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

		//var_dump($list);die;

		$this->smarty->assign('list',$list);
		$this->smarty->assign('limit',$limit);

		$this->smarty->display('HouseWork/index_offline.html');
	}

	//活动编辑页
	public function edit(){
		$uid = session(C('USER_AUTH_KEY'))+0;
		$id=I('post.id',0,'int');
		unset($_POST['id']);
		$data=HouseWorkModel::getItemInstance()->create();


		//自动完成 将时间自动转换为时间戳
		$content=htmlspecialchars_decode(I('post.detail'));
		$nativeRT	= UtilsModel::NativeThumb($content);
		$relativePhoto	= $nativeRT[0];
		$content		= $nativeRT[1];


		$data['detail'] = $content;
		$data['beginShowTime'] = strtotime($data['beginShowTime']);
		$data['album'] = implode(',',I('post.album'));
		$name=I('post.name',null);
		$fee=I('post.fee',null);
		$unit=I('post.unit',null);
		$point=I('post.point',null);
		$reduce=I('post.reduce',null);
		if (!$name || !$fee || !$unit || count($name)!=count($fee) || count($name)!=count($unit)){
			$this->ajaxReturn( array('status'=>1, 'msg'=> '价格配置错误！') );
		}

		$setArr=[];
		foreach ($name as $k=>$v){
			$setArr[]="{$v}/{$fee[$k]}/{$unit[$k]}/{$point[$k]}/{$reduce[$k]}";
		}
		$data['price']=implode(';',$setArr);

		$events = HouseWorkModel::getItemInstance();
		if($id){
			$events->where("id=$id")->save($data);
			$this->ajaxReturn( array('status'=>0, 'msg'=> '家政项目修改成功！', 'id'=>$id) );
		}else{
			$row = $events->where("title='{$data['title']}'")->find();
			if($row) $this->ajaxReturn( array('status'=>1, 'msg'=> '该项目名称已存在！') );
			$data['addTime'] = time();
			$insertid = $events->add($data);

			$this->ajaxReturn( array('status'=>0, 'msg'=> '新增项目成功！', 'id'=>$insertid) );
		}

	}

	//活动添加页
	public function add(){
		$id=I('get.id',0,'int');

		$priceSet=[];
		if($id){
			$events = HouseWorkModel::getItemInstance();
			$data = $events->where("id=$id")->find();
			$this->smarty->assign('data', $data);
			$this->smarty->assign('id', $id);

			$set=explode(';',$data['price']);

			foreach ($set as $one){
				if (!$one) continue;
				list($name,$price,$unit,$point,$reduce)=explode('/',$one);
				if ($unit){
					$priceSet[]=[$name,$price,$unit,$point,$reduce];
				}
			}
		}

		if (count($priceSet)==0){
			$priceSet[]=['','',''];
		}
		$this->smarty->assign('priceSet', $priceSet);

		$this->smarty->assign('picWidth', C("EVENTS_THUMB_WIDTH"));
		$this->smarty->assign('picHeight', C("EVENTS_THUMB_HEIGHT"));

		$this->smarty->display('HouseWork/edit.html');
	}








	//报名列表
	public function orderList(){
		$where = " 1 ";
		$export = I('get.export',0,'int');
		$nickname = I('get.nickname',null);
		if($nickname){
			$where .= " AND nickname like '%$nickname%' ";
			$this->smarty->assign('nickname',$nickname);
		}

		$status = I('get.status',null);
		if($status){
			$where .= " AND status = '$status' ";
			$this->smarty->assign('status',$status);
		}
		$item = I('get.item',0);
		if($item){
			$where .= " AND itemId = '$item' ";
			$this->smarty->assign('item',$item);
		}

		$phone = I('get.phone',null);
		if($phone){
			$where .= " AND phoneNumber like '%$phone%' ";
			$this->smarty->assign('phone',$phone);
		}

		$beginShowTime=I('get.beginShowTime');
		if($beginShowTime){
			$time=strtotime($beginShowTime);
			if ($time>0) {
				$where .= " AND addTime >= {$time}";
				$this->smarty->assign('beginShowTime', $beginShowTime);
			}
		}

		$endShowTime=I('get.endShowTime');
		if($endShowTime){
			$time=strtotime($endShowTime);
			if ($time>0) {
				$where .= " AND addTime < {$time}";
				$this->smarty->assign('endShowTime', $endShowTime);
			}
		}



		$orderM = HouseWorkModel::getOrderInstance();



		import("ORG.Util.Page");
		$temp=$orderM->where($where);
		$count = $temp->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty, $Page);
		$ym=date('Y-m',time());
		list($nowYear,$nowMonth)=explode('-',$ym);

		$statusKV=HouseWorkModel::getOrderStatusKv();

		if($export){

			$list = $orderM->order('id desc')->where($where)->select();
			$data = array();
			foreach ($list as $key => $val){
				$data[$key]['addTime'] = date('Y-m-d H:i:s',$val['addTime']);
				$data[$key]['phone'] = $val['phoneNumber'];
				$data[$key]['nickname'] = $val['nickname'];
				$data[$key]['orderTime'] = $val['orderTime'];
				$data[$key]['itemName'] = $val['itemName'];
				$data[$key]['itemDetail'] = $val['itemDetail'];
				$data[$key]['price'] = $val['price'];
				$data[$key]['status'] = $statusKV[$val['status']];
				$data[$key]['address'] = $val['area'].'.'.$val['address'];
				$data[$key]['score'] = intval($val['score']);
				$data[$key]['comment'] = $val['comment'];
			}
			exportExcel($data, array('订单时间','手机号码','昵称','预约时间','项目','项目详情','预估价格','状态','地址','评分','评价'),'家政订单');
			exit;
		}
		else{
			$list = $orderM->order('id desc')->where($where)->limit($Page->firstRow.','.$Page->listRows)->select();

			$this->smarty->assign('list',$list);
			$this->smarty->assign('statusKv',$statusKV);
			$this->smarty->assign('itemKv',HouseWorkModel::getItemKv());
			$this->smarty->assign('IS_FINISH',HouseWorkModel::ORDER_STATUS_COMPLETE);
			$this->smarty->assign('IS_CANCEL',HouseWorkModel::ORDER_STATUS_CANCEL);
			$this->smarty->assign('IS_ASSIGN',HouseWorkModel::ORDER_STATUS_ASSIGN);
			$this->smarty->assign('IS_INIT',HouseWorkModel::ORDER_STATUS_INIT);
			$this->smarty->assign('limit',$limit);
			


			$this->smarty->display('HouseWork/orderList.html');
		}

	}


	public function changeTime(){
		$id = I("get.id",0,'int');
		$time= I("get.time",null);
		if(!$id||!$time||strtotime($time)==0){
			$this->ajaxReturn(array('status'=>1, 'msg'=>'参数错误'));
		}

		$record=HouseWorkModel::getOrderInstance()->find($id);
		if (!$record){
			$this->ajaxReturn(array('status'=>1, 'msg'=>'指定的订单不存在'));
		}

		list($date,$hour)=explode(' ',$time);
		if(!HouseWorkModel::getTimeOrder($record['itemId'],$date,$hour)){
			$this->ajaxReturn(array('status'=>1, 'msg'=>'指定时间排班已满'));
		}


		list($oldDate,$oldHour)=explode(' ',$record['orderTime']);
		HouseWorkModel::timeOrderReduce($record['itemId'],$oldDate,$oldHour);
		HouseWorkModel::getOrderInstance()->where("id={$id}")->setField('orderTime',$time);
		HouseWorkModel::timeOrderPlus($record['itemId'],$date,$hour);



		if (strlen($record['phoneNumber'])>7) {
			$param = [
				'item'    => $record['itemName'],
				'oldtime' => $record['orderTime'],
				'newtime' => $time
			];
			SmsModel::sendSms($record['phoneNumber'], SmsModel::SMS_TPL_HOUSEWORK_CHANGE, $param);
		}
		$this->ajaxReturn(array('status'=>0, 'msg'=>'操作成功'));


	}

	//查看用户详情(状态)
	public function changeStatus(){
		$id = I("get.id",0,'int');
		$act= I("get.act",null);
		if($id<=0){
			$this->ajaxReturn(array('status'=>1, 'msg'=>'请指定记录'));
		}
		$html='';
		switch (strtoupper($act)){
			case 'FINISH':
				$status=HouseWorkModel::ORDER_STATUS_COMPLETE;
				//$html="<a href=\"javascript:cancel('{$id}');\">取消</a>";
				break;
			case 'CANCEL':
				$status=HouseWorkModel::ORDER_STATUS_CANCEL;


				//$html="<a href=\"javascript:finish('{$id}');\">完成</a>";
				break;
			case 'ASSIGN':
				$status=HouseWorkModel::ORDER_STATUS_ASSIGN;
				$html="<a href=\"javascript:cancel('{$id}');\">取消</a><a href=\"javascript:finish('{$id}');\">完成</a><a href=\"javascript:edit('{$id}');\">修改</a>";
				break;
			default:
				$this->ajaxReturn(array('status'=>1, 'msg'=>'错误的操作类型'));
		}

		$record=HouseWorkModel::getOrderInstance()->find($id);
		if (!$record){
			$this->ajaxReturn(['status'=>1,'msg'=>'指定的订单不存在']);
		}
		if ($record['status']==HouseWorkModel::ORDER_STATUS_COMPLETE || $record['status']==HouseWorkModel::ORDER_STATUS_CANCEL){
			$this->ajaxReturn(['status'=>1,'msg'=>'已取消或者已完成的订单不可操作']);
		}


		HouseWorkModel::getOrderInstance()->startTrans();
		if ($status==HouseWorkModel::ORDER_STATUS_CANCEL && $record['point']>0){
			$tempR=UserModel::plusPoint($record['uid'],-1,$record['point'],OPT_CANCEL_HOUSEWORK,"{$id}|{$record['itemDetail']}");
			if ($tempR['status']!=0){
				HouseWorkModel::getItemInstance()->rollback();
				$this->ajaxReturn(['status'=>1,'msg'=>'操作失败，请稍后重试']);
			}
		}
		$result=HouseWorkModel::getOrderInstance()->where("id={$id}")->setField('status',$status);
		if ($result==false){
			HouseWorkModel::getItemInstance()->rollback();
			$this->ajaxReturn(array('status'=>1, 'msg'=>'设置失败'));
		}
		if($status==HouseWorkModel::ORDER_STATUS_CANCEL) {
			list($date, $hour) = explode(' ', $record['orderTime']);
			HouseWorkModel::timeOrderReduce($record['itemId'], $date, $hour);
		}

		HouseWorkModel::getOrderInstance()->commit();

		$tpl='';
		$now=time();
		switch ($status){
			case HouseWorkModel::ORDER_STATUS_ASSIGN:
				$tpl=SmsModel::SMS_TPL_HOUSEWORK_ASSIGN;
				$param=[
					'item'=>'('.$record['itemName'].')',
					'time'=>$record['orderTime'],
				];
				break;
			case HouseWorkModel::ORDER_STATUS_CANCEL:
				$tpl=SmsModel::SMS_TPL_HOUSEWORK_CANCEL;
				$param=[
					'item'=>'('.$record['itemName'].')',
					'time'=>date('m-d H:i',$now),
				];
				break;
			case HouseWorkModel::ORDER_STATUS_COMPLETE:
				$tpl=SmsModel::SMS_TPL_HOUSEWORK_COMPLETE;
				$param=[
					'item'=>'('.$record['itemName'].')',
					'money'=>$record['price'],
					'time'=>date('m-d H:i',$now),
				];
				break;
		}



		if ($tpl!='' && strlen($record['phoneNumber'])>7) {
			$result=SmsModel::sendSms($record['phoneNumber'], $tpl,$param);
		}

		$statusKv=HouseWorkModel::getOrderStatusKv();
		$statusName=$statusKv[$status];
		$this->ajaxReturn(array('status'=>0, 'html'=>$html,'statusName'=>$statusName));
	}





}




